// https://www.lintcode.com/problem/construct-string-from-binary-tree/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param t: the root of tree
     * @return: return a string
     */
    public String tree2str(TreeNode t) {
        // write your code here
        StringBuilder sb = new StringBuilder();
        if (t != null) {
            sb.append(t.val);
            if (t.left != null) {
                String ls = tree2str(t.left);
                sb.append('(');
                sb.append(ls);
                sb.append(')');
            }
            if (t.right != null) {
                if (t.left == null) {
                    sb.append("()");
                }
                String rs = tree2str(t.right);
                sb.append('(');
                sb.append(rs);
                sb.append(')');
            }
        }
        return sb.toString();
    }
}